﻿CREATE PROCEDURE [dbo].[yaf_message_delete](
                @MessageID INT)
AS
    BEGIN
        DECLARE  @TopicID INT
        DECLARE  @ForumID INT
        DECLARE  @MessageCount INT
        DECLARE  @LastMessageID INT
        -- Find TopicID and ForumID
        SELECT @TopicID = b.TopicID,
               @ForumID = b.ForumID
			FROM   yaf_Message a,
				   yaf_Topic b
			WHERE  a.MessageID = @MessageID
			AND b.TopicID = a.TopicID
        -- Update LastMessageID in Topic and Forum
        UPDATE yaf_Topic
			SET    LastPosted = NULL,
				   LastMessageID = NULL,
				   LastUserID = NULL,
				   LastUserName = NULL
			WHERE  LastMessageID = @MessageID
			UPDATE yaf_Forum
			SET    LastPosted = NULL,
				   LastTopicID = NULL,
				   LastMessageID = NULL,
				   LastUserID = NULL,
				   LastUserName = NULL
			WHERE  LastMessageID = @MessageID
        -- "Delete" message
        UPDATE yaf_Message
			SET    Flags = Flags | 8
			WHERE  MessageID = @MessageID
        -- Delete topic if there are no more messages
        SELECT @MessageCount = COUNT(1)
			FROM   yaf_Message
			WHERE  TopicID = @TopicID
			AND (Flags & 8) = 0
        IF @MessageCount = 0
			EXEC yaf_topic_delete
				 @TopicID
        -- update lastpost
        EXEC yaf_topic_updatelastpost
             @ForumID ,
             @TopicID
        EXEC yaf_forum_updatestats
             @ForumID
        -- update topic numposts
        UPDATE yaf_Topic
			SET    NumPosts = (SELECT COUNT(1)
							   FROM   yaf_Message x
							   WHERE  x.TopicID = yaf_Topic.TopicID
							   AND (x.Flags & 24) = 16)
			WHERE  TopicID = @TopicID
		-- update user's numposts
		UPDATE yaf_User
			SET NumPosts=NumPosts-1
			WHERE UserID=(SELECT UserID FROM yaf_Message WHERE MessageID = @MessageID)
    END


